<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>练习前后端交互</title>
	</head>
	<body>
		<div id="app">
			
			<table align="center" border="2px" width="80%">
				<tr>
					<h1 align="center">用户列表</h1>
				</tr>
				<tr align="center">
					<td>id</td>
					<td>姓名</td>
					<td>年龄</td>
					<td>性别</td>
					<td>操作</td>
				</tr>
				<tr align="center" v-for="user in userList">
					<td v-text="user.id"></td>
					<td v-text="user.name"></td>
					<td v-text="user.age"></td>
					<td v-text="user.sex"></td>
					<td>
						<button @click="update1(user.id)">修改</button>
						<button @click="deleteUser(user.id)">删除</button> <!-- 用含参方法,传输id -->
					</td>
				</tr>
			</table>
			<div align="center" >
				<h1 >用户新增</h1>
					name <input type="text" width="80px" v-model.trim="addUser.name">
					age <input type="text" width="80px" v-model.number="addUser.age">
					sex <input type="text" width="80px" v-model.trim="addUser.sex">
					<button @click="add()">新增</button>
					
				
			</div>
			<hr >
			<div align="center" >
				<h1 >用户修改</h1>
					id <input type="text" width="80px" v-model.trim="updateUser.id">
					name <input type="text" width="80px" v-model.trim="updateUser.name">
					age <input type="text" width="80px" v-model.number="updateUser.age">
					sex <input type="text" width="80px" v-model.trim="updateUser.sex">
					<button @click="update2()">修改</button>
			</div>
		</div>
		<script src="../js/vue.js"></script>
		<script src="../js/axios.js"></script>
		<script>
			axios.defaults.baseURL="http://localhost:8070/user"
			const app = new Vue({
				el: "#app",
				data: {
					userList: [],
					addUser: {
						name: "",
						age: "",
						sex: ""
					},
					updateUser: {
						id: "",
						name: "",
						age: "",
						sex: ""
					}
					
				},
				methods: {
					async getAll(){
						let{data:result}=await axios.get("/getAll")
						console.log(result)
						this.userList = result
					},
					async add(){
						await axios.post("/insert",this.addUser)//this要点.
						this.getAll()
					},
					async deleteUser(id){
						await axios.delete(`/delete/${id}`)//this要点.
						this.getAll()
					},
					update1(id){/* 方法名和data的参数名字不要一样,否则识别不到方法 */
						
						this.updateUser.id=id
					},
					async update2(){
						await axios.put("/updateUser",this.updateUser)
						this.getAll()
					}
					
					
				},
				mounted(){
					this.getAll();
				}
			})
		</script>
	</body>
</html>
